<?php

namespace Set\Controller;

use Common\Controller\BaseController;
use Think\Page;

class NoticeController extends BaseController
{
    public function index()
    {
        $model = D('Notice');
        $sp = $_GET['p'];
        if (empty($sp)) {
            $sp = 1;
        }
        $search_key = $_POST['search_key'];
        $status = $_POST['search_status'];
        $list = $model->get_list($search_key, $status, $sp, C('PAGE_SIZE'));

        $page = new Page($list[1], C('PAGE_SIZE'));

        $this->assign('total_rows', $page->totalRows);
        $this->assign('_page', $page);
        $this->assign('page_link', $page->show());
        $this->assign('notice_list', $list[0]);

        foreach ($_POST as $key => $val) {
            $page->parameter[$key] = urlencode($val);
        }
        $this->display();
    }

    public function save()
    {
        $model = D('Notice');
        $data = $model->create();
        $curren_status = $_POST['curren_status'];

        if (!$data) { //数据对象创建错误
            echo '数据对象创建错误';
        } else {
            if (empty($data['id'])) {
                $data['create_at'] = time();
            }

            $result = $model->update($data);

            if (!$result) {
                echo $model->getError();
            } else {
                if ($data['status'] == '1' && empty($curren_status)) {
                    $user_list = fc_get_user_list();

                    $UserNotice = M('user_notice');
                    $dataList = [];
                    foreach ($user_list as $user) {
                        if ($data['rank'] == 0 || $user['rank'] == $data['rank']) {
                            if ($data['attribute'] == 0 || $user['role'] != 3 || ($user['role'] == 3 && $user['attribute'] == $data['attribute'])) {
                                $dataList[] = array('user_id' => $user['id'], 'notice_id' => $result);
                            }
                        }
                    }
                    $UserNotice->addAll($dataList);
                }
                echo '0';
            }
        }
        exit();
    }

    public function delete()
    {
        $id = $_GET['id'];

        $model = D('Notice');
        $result = $model->delete($id, $this->current_user['id']);
        if (!$result) {
            echo $model->getError();
        } else {
            echo '0';
        }
        exit();
    }
}
